package net.asfun.jvalog.frame;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.asfun.jvalog.common.DualCacher;
import net.asfun.jvalog.common.InteractException;
import net.asfun.jvalog.mvc.HandlerInterceptor;
import net.asfun.jvalog.mvc.ModelAndView;
import net.asfun.jvalog.vo.Site;


import static net.asfun.jvalog.common.log.logger;

public class ReadCacheInterceptor implements HandlerInterceptor{

	public static final String PATH_PARAM = "UNI_PATH";
	
	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse resp, Object controller, Exception e)
			throws Exception {
		if ( e != null ) {
			String path = (String) req.getAttribute(PATH_PARAM);
			logger.fine("Request " + path + " causes exception：" + e.getMessage());
			if ( e instanceof InteractException ) {
				if ( path.equals("404") ) {
					resp.sendError(500);
				} else {
					resp.sendError(404);
				}
			} else {
				if ( path.equals("500") ) {
					resp.sendRedirect(Site.getInstance().getUrl());
				} else {
					resp.sendError(500);
				}
			}
		}
		resp.setHeader("Cache-Control", "max-age=1728000, public");
		resp.setHeader("Pragma", "cache");
		long now = new Date().getTime();
		long next = now + 1728000000;//20 day
		resp.setDateHeader("Last-Modified", now);
		resp.setDateHeader("Expires", next);
		resp.setHeader("ETag", Long.toString(now, 32));
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp,
			Object controller, ModelAndView mav) throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
			Object controller) throws Exception {
		String uri = req.getRequestURI();
		uri = uri.substring(1);
		int ext = uri.lastIndexOf('.');
		if ( ext > 0 ) {
			uri = uri.substring(0, ext);
		}
		if ( uri.endsWith("/") ) {
			uri = uri.substring(0, uri.length()-1);
		}
		logger.info("path=" + uri);
		req.setAttribute(PATH_PARAM, uri);
		resp.setContentType("text/html; charset=utf-8");
		//use if cached
		String cache = DualCacher.get(uri);
		if ( cache != null ) {
//			resp.setCharacterEncoding("utf-8");
			resp.getWriter().print(cache);
			return false;
		}
		return true;
	}

}
